package com.zzty.txj.controller;

import com.zzty.txj.entity.Daily;
import com.zzty.txj.entity.DoDaily;
import com.zzty.txj.entity.User;
import com.zzty.txj.service.DailyService;
import com.zzty.txj.service.DoDailyService;
import com.zzty.txj.service.UserService;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/doDaily")
public class DoDailyController {

    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(DoDailyController.class);

    @Autowired
    DoDailyService doDailyService;

    @Autowired
    DailyService dailyService;

    @Autowired
    UserService userService;

    @RequestMapping(value = "/getRecordByDateAndId", method = RequestMethod.POST)
    public Map getRecordByDateAndId(DoDaily doDaily) {
        Map<Object, Object> map = new HashMap<>();
        logger.info("date " + doDaily.getDate() + " userId: " + doDaily.getUserId());

        List<DoDaily> records = doDailyService.getRecordByDateAndId(doDaily);
        if (records != null) {
            for (DoDaily doDaily1 : records) {
                Daily daily = dailyService.getDailyById(doDaily1.getDailyId());
                String dailyName = daily.getName();
                doDaily1.setDailyName(dailyName);

                User user = userService.getUserById(doDaily1.getUserId());
                String userName = user.getName();
                doDaily1.setUserName(userName);
                logger.info("doDaily1 getUserName: " + doDaily1.getUserName());

            }
            map.put("records", records);
            logger.info("map records: " + map);

        } else {
            map.put("records", 0);
        }
        return map;
    }

    @RequestMapping(value = "/updateRecordById/{id}", method = RequestMethod.GET)
    public Integer updateRecordById(@PathVariable("id") Integer id) {
        logger.info("doDaily/updateRecordById/{id}" + id);
        DoDaily doDaily = doDailyService.getDoDailyById(id);

        if (doDaily.getResult() == 1) {
            doDaily.setFinalResult(-1);
        } else if (doDaily.getResult() == -1) {
            doDaily.setFinalResult(1);
        }else if(doDaily.getResult()==null){
            doDaily.setFinalResult(-1);
        }
        Integer count = doDailyService.updateRecordById(doDaily);
        logger.info("doDaily: " + doDaily.toString());
        return count;
    }

    @RequestMapping("/getDoDailyById/{id}")
    public DoDaily getDoDailyById(@PathVariable("id") Integer id) {
        DoDaily doDaily = doDailyService.getDoDailyById(id);
        if (doDaily != null) {
            logger.info("getDoDailyById: " + doDaily.toString());
            return doDaily;
        } else {
            return null;
        }
    }
}
